<?php
/**
 * 用户留言管理
 */
class MessageApp extends CommonApp {
	
	private $table = 'message';

	/**
	 * 首页
	 */
	public function indexAct(){
		//search
		$search = array();
		$search['where'] = "A.item != 'reply' ";
		$search['page'] = My::arr2var($_REQUEST,'page').(isset($_SESSION['pagesize'])?$_SESSION['pagesize']:'');//用于参与缓存标识	
		$search['join'] = "#__message as A ";
        $search['join'] .= "LEFT JOIN #__member as B ON A.member_id=B.id ";
        $search['field'] = "A.*,B.username,B.nickname";
        $search['order'] = "A.id DESC";
		//搜索标题
		if(My::arr2var($_GET,'title')!=''){
			$title = I('get.title');
			$search['where'] .= "AND A.`title` like '%{$title}%' ";
		}
		//搜索内容
		if(My::arr2var($_GET,'content')!=''){
			$content = I('get.content');
			$search['where'] .= "AND A.`content` like '%{$content}%' ";
		}
		//搜索留言者
		if(My::arr2var($_GET,'username')!=''){
			$username = I('get.username');
			$search['join'] = "#__message as A INNER JOIN #__member as B ON A.member_id=B.id AND (B.username like '%{$username}%' OR B.nickname like '%{$username}%')";
		}
		//搜索手机
		if(My::arr2var($_GET,'tel')!=''){
			$tel = I('get.tel');
			$search['where'] .= "AND A.`tel` like '%{$tel}%' ";
		}
		//搜索邮箱
		if(My::arr2var($_GET,'email')!=''){
			$email = I('get.email');
			$search['where'] .= "AND A.`email` like '%{$email}%' ";
		}
		//搜索id
		if(My::is_id(My::arr2var($_GET,'id'))){
			$id = $_GET['id'];
			$search['where'] .= "AND A.`id`='{$id}' ";
		}
		//搜索留言类型
		if(My::arr2var($_GET,'type')!=''){
			$item = I('get.item');
			$search['where'] .= "AND A.`item`='{$item}' ";
		}
		
		//状态
		$status = I('get.status');
		if($status!=''){
		    $search['where'] .= "AND A.status='{$status}' ";
		}
		$start = I('get.start_date');;
		$end = I('get.end_date');
		//查询起始时间
		if(My::is_date($start,'Y-m-d')){
		    $search['where'] .= "AND A.`adddate`>='{$start} 00:00:00' ";
		}
		//查询结束时间
		if(My::is_date($end,'Y-m-d')){
		    $search['where'] .= "AND A.`adddate`<='{$end} 23:59:59' ";
		}

		$result=My::getCache($search,array('pre'=>$this->table));
		if($result==''){
			//page
			$total_sql = DB('')->table($search['join'])->field('1')->where($search['where'])->group('A.id')->select(false);
			$result['page'] = My::page(My::sql2count($total_sql));
			//result
			$result['data'] = DB('')->field($search['field'])->join($search['join'])->where($search['where'])->group('A.id')->order($search['order'])->limit($result['page']['limits'])->select();
			if(is_array($result['data'])){
			    foreach($result['data'] as &$value){
			        $value['params'] = My::decodeJson($value['params']);
			        $value['reply'] = DB('message')->where("item='reply' AND idid='{$value['id']}'")->order('id DESC')->cache()->find();
			    }
			}
			// echo DB('')->getLastSql();
			My::setCache($search,$result,array('pre'=>$this->table));
		}
		$this->assign('result',$result);
		//print_r($result);
		//display
		$this->display("Message/index");
	}
	
	
	/**
	 * 回复
	 * @params $_REQUEST['id']
	 */
	public function replyAct(){
	    $idid = My::arr2var($_REQUEST,'idid');
	    if(!My::is_id($idid))
	        $this->ajaxReturn(404, 'ID无效!');
        if($_POST){
            if(!token())
                $this->ajaxReturn(300,'令牌验证错误!');
            if(empty($_POST['content']))
                $this->ajaxReturn(300,'回复内容不能为空!');
            $data['content'] = My::arr2var($_POST,'content');
            $data['idid'] = $idid;
            $data['item'] = 'reply';
            $data['adddate'] = date("Y-m-d H:i:s");
            $data['ip'] = get_client_ip();
            $data['author'] = My::user('username');
            $ok = DB('message') ->clear()->add($data);
            if($ok){
                self::sendEmail($data);
                $this->ajaxReturn(200,"回复成功");
            }else
                $this->ajaxReturn(300,"回复失败");
        }
        $this->display();
	}
	
	/**
	 * 发邮件
	 */
	private function sendEmail($data){
	    $emailParam['title'] = '留言回复';
        $emailParam['content'] = str_replace("\r\n","<br>",$data['content']);
        $oMessage = My::id2detail('message',$data['idid']);
        if(!$oMessage or $oMessage<0)
            return false;
        if(!My::is_email($oMessage['email']))
            return false;
        $oContent = str_replace("\r\n","<br>",$oMessage['content']);
        $emailParam['content'] .= "<br>------------------ 原始留言 ------------------<br><div style='font-size: 12px; background: #efefef; padding: 8px;'>{$oContent}</div>";
        $emailParam['receiver'] = array($oMessage['email']);
        $sendok = My::sendApiMail($emailParam);
        if($sendok==true)
            return true;
        else
            return false;
	}
	
	

	public function processAct(){
	    $id = My::arr2var($_REQUEST,'id');
	    if(!My::is_id($id))
	        $this->ajaxReturn(404, 'ID无效!');
	        $result = My::id2detail('message',$id);
	        if(!$result or $result<0)
	            $this->ajaxReturn(404, '数据不存在!');
	            if($_POST){
	                $status = My::arr2var($_POST,'status');
	                if(!in_array($status,array('0','1','2')))
	                    $this->ajaxReturn(300, '请选择状态!');
	                    $params = $result['params'];
	                    $params['remark'] = My::arr2var($_POST,'remark');
	                    $ok = DB($this->table)->where("id = ({$id})")->clear()->save(array('status'=>$status,'params'=>$params));
	                    if($ok)
	                        $this->ajaxReturn(200,"处理成功");
	                        else
	                            $this->ajaxReturn(300,"处理失败");
	            }
	            $this->assign('result',$result);
	            $this->display();
	
	}
	
	
	public function batAct(){
	    if($_POST){
	        $ids = My::arr2var($_POST,'ids');
	        $status = My::arr2var($_POST,'status');
	        if($ids=='')
	            $this->ajaxReturn(300, 'ID不能为空!');
	            if(!My::is_ids($ids))
	                $this->ajaxReturn(300, 'ID无效!');
	                if(!in_array($status,array('0','1','2')))
	                    $this->ajaxReturn(300, '请选择状态!');
	                    $ok = DB($this->table)->where("id IN ({$ids}) AND item!='reply'")->clear()->save(array('status'=>$status));
	                    if($ok)
	                        $this->ajaxReturn(200,"批量处理成功");
	                        else
	                            $this->ajaxReturn(300,"批量处理失败");
	    }
	    $this->display("",$_GET);
	}
	
	
	/**
	 * 导出Excel
	 * @params string $_GET['day'] 日期
	 */
	public function exportAct(){
	    //search
	    $search = array();
	    $search['where'] = "1 ";
	    $search['where'] .= "AND A.`item`!='reply' ";
	    //状态
	    $status = I('get.status');
	    if($status!=''){
	        $search['where'] .= "AND A.status='{$status}' ";
	    }
	    $search['field'] = "A.*,B.username,B.id AS uid";
	    $search['page'] = 'ALL';//用于参与缓存标识
	    $search['table'] = "#__{$this->table} as A";
	    $search['join'] = "LEFT JOIN #__member as B ON A.member_id=B.id ";
	    //搜索标题
	    $title = I('get.title');
	    if($title!=''){
	        $title = I('get.title');
	        $search['where'] .= "AND A.`title` like '%{$title}%' ";
	    }
	    //搜索id
	    $id = My::arr2var($_GET,'id');
	    if(My::is_id($id)){
	        $search['where'] .= "AND A.`id`='{$id}' ";
	    }
	    $start = I('get.start_date');;
	    $end = I('get.end_date');
	    //查询起始时间
	    if(My::is_date($start,'Y-m-d')){
	        $search['where'] .= "AND A.`adddate`>='{$start} 00:00:00' ";
	    }
	    //查询结束时间
	    if(My::is_date($end,'Y-m-d')){
	        $search['where'] .= "AND A.`adddate`<='{$end} 23:59:59' ";
	    }
	    $search['order'] = 'A.adddate DESC,A.id DESC';
	    $result=My::getCache($search,array('pre'=>$this->table));
	    if($result==''){
	        $result = DB('')->table($search['table'])->field($search['field'])->join($search['join'])->where($search['where'])->group('A.id')->order($search['order'])->select();
	        //echo DB('')->getLastSql();
	        if(is_array($result))
	            foreach($result as &$value){
	                $value['params'] = My::decodeJson($value['params']);
	        }
	        My::setCache($search,$result,array('pre'=>$this->table));
	    }
	
	    set_time_limit(0);
	    $data[0] = array(
	        'type' => '留言内容',
	        'content' => '留言内容',
	        'member' => '留言用户',
	        'adddate' => '时间',
	        'status' => '状态',
	        'remark' => '处理备注',
	    );
	    $data2 = array();
	    $message_status = C('message_status');
	    $message_type = C('message_type');
	    if($result){
	        foreach($result as $key=>&$value){
	            $row = array(
	                'type' => My::arr2var($message_type,$value['item']),
	                'content' => My::arr2var($value,'content'),
	                'member' => My::arr2var($value,'username')."（ID：".My::arr2var($value,'uid')."）",
	                'adddate' => My::arr2var($value,'adddate'),
	                'status' => My::arr2var($message_status,$value['status']),
	                'remark' => My::arr2var($value,'params.remark'),
	            );
	            $data2[] = $row;
	        }
	    }
	    $data = array_merge($data, $data2);
	    $filename = '留言';
	    // print_r($data);exit;
	    if($start and $end)
	        $filename .= '_'.$start.'至'.$end.'';
        else if($start)
            $filename .= '_'.$start.'至现在';
        else if($end)
            $filename .= '_'.$end.'前';
        if($status!='')
            $filename.='_'.$message_status[$status];
        if($title!='')
            $filename.='_'.$title;
        if($id!='')
            $filename.='_'.$id;

        $filename = iconv('UTF-8','GBK',$filename);
        $savepath = DATA_DIR.'/Cache/';
        $xls = new Excel('UTF-8', false, 'delivery');
        $xls->addArray($data);
        $xls->saveXLS(md5(My::encodeJson($data)), $savepath);
        $xls->downloadXLS($savepath.md5(My::encodeJson($data)), $filename);
	}
}